from sqlalchemy import Boolean, Column, DateTime, Enum, Integer, String, Text, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.db.database import Base
import enum

class ChatType(str, enum.Enum):
    """聊天类型枚举"""
    PRIVATE = "private"  # 私聊
    GROUP = "group"      # 群聊
    SYSTEM = "system"    # 系统消息


class Chat(Base):
    """聊天会话模型"""
    __tablename__ = "chats"

    id = Column(Integer, primary_key=True, index=True)
    chat_type = Column(Enum(ChatType), default=ChatType.PRIVATE)
    name = Column(String(100), nullable=True)  # 群聊名称，私聊为空
    campsite_id = Column(Integer, ForeignKey("campsites.id"), nullable=True)  # 关联的营地ID（如果是营地群聊）
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # 关系
    messages = relationship("Message", back_populates="chat", cascade="all, delete-orphan")
    participants = relationship("ChatParticipant", back_populates="chat", cascade="all, delete-orphan")


class ChatParticipant(Base):
    """聊天参与者模型"""
    __tablename__ = "chat_participants"

    id = Column(Integer, primary_key=True, index=True)
    chat_id = Column(Integer, ForeignKey("chats.id"))
    user_id = Column(Integer, ForeignKey("users.id"))
    is_admin = Column(Boolean, default=False)  # 是否为群管理员
    last_read_message_id = Column(Integer, ForeignKey("messages.id"), nullable=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # 关系
    chat = relationship("Chat", back_populates="participants")
    user = relationship("User")


class Message(Base):
    """消息模型"""
    __tablename__ = "messages"

    id = Column(Integer, primary_key=True, index=True)
    chat_id = Column(Integer, ForeignKey("chats.id"))
    sender_id = Column(Integer, ForeignKey("users.id"), nullable=True)  # 系统消息可能没有发送者
    content = Column(Text)
    content_type = Column(String(20), default="text")  # text, image, video, audio, file
    media_url = Column(String(255), nullable=True)  # 媒体URL（如果是媒体消息）
    is_read = Column(Boolean, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    # 关系
    chat = relationship("Chat", back_populates="messages")
    sender = relationship("User")
    read_by = relationship("ChatParticipant", primaryjoin="Message.id==ChatParticipant.last_read_message_id") 